package qdu.edu.cn.jdbc;

import java.sql.*;

public class MySQLDataBaseConnection {
    private static final String userName = "root";
    private static final String password = "666666";
    private static final String url = "jdbc:mysql://liu:3306/ProductDescriptionAnalysis_All";
    private Connection connection;

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public MySQLDataBaseConnection() {
        try {
            connection = DriverManager.getConnection(url, userName, password);
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }

    public void closeConnection() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException sqlException) {
                sqlException.printStackTrace();
            }
        }
    }

    public String select(String selectString, int times ) {
        String[] str = {"set @str='" +selectString+ "';", "set @times="+times+";", "call select_1(@str, @times);"};
        String result = null;

        try (
                Statement ps = connection.createStatement()
        ) {
            ps.addBatch(str[0]);
            ps.addBatch(str[1]);
            ps.executeBatch();
            ResultSet resultSet = ps.executeQuery(str[2]);
            while (resultSet.next()) {
                result = resultSet.getString("@out_str");
            }
            resultSet.close();
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }

        return result;
    }
}
